package com.wang.tool.webtool;

import com.wang.tool.util.SimpleLogUtil;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;

import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * web工具bean注入
 *
 * @Author wangshaopeng
 * @Date 2021/1/7
 */
public class WebToolRegister implements ImportBeanDefinitionRegistrar {

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        AnnotationAttributes tooAttr = AnnotationAttributes.fromMap(importingClassMetadata.getAnnotationAttributes(EnableWebTool.class.getName()));

        //errorResponse
        Class modelBuilderClass = tooAttr.getClass("errorBuilder");
        if (WebErrorResponseBuilder.class.equals(modelBuilderClass)) {
            throw new IllegalArgumentException("errorBuilder is not valid ,please check has no param constructor!");
        }
        BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(modelBuilderClass);
        registry.registerBeanDefinition(WebErrorResponseBuilder.class.getName(), builder.getBeanDefinition());
        SimpleLogUtil.info("[setWebErrorResponseBuilder], webErrorResponseBuilder:{0}", modelBuilderClass.getName());


        //注入dateConverter,帮助参数转换Date,主要为了实现注解自定义日期格式化
        BeanDefinitionBuilder dateConfigBuilder = BeanDefinitionBuilder.genericBeanDefinition(WebDateConverterConfig.DateFormatConfig.class);
        //反序列化
        String[] dateDeserializeFormats = tooAttr.getStringArray("dateDeserializeFormats");
        if (dateDeserializeFormats.length == 0) {
            throw new IllegalArgumentException("dateDeserializeFormatter can not be null!");
        }
        dateConfigBuilder.addPropertyValue("dateDeserializeFormats", Arrays.stream(dateDeserializeFormats).collect(Collectors.toList()));

        //序列化
        String serializeFormat = tooAttr.getString("dateSerializeFormat");
        dateConfigBuilder.addPropertyValue("dateSerializeFormat", serializeFormat);
        registry.registerBeanDefinition(WebDateConverterConfig.DateFormatConfig.class.getName(), dateConfigBuilder.getBeanDefinition());
        SimpleLogUtil.info("[setDateFormatConfig], deserializeFormatters:{0}, dateSerializeFormat:{1}", dateDeserializeFormats, serializeFormat);

    }
}
